package com.hengtiansoft.lfy.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.EvaluatorModeEntity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by suyiyang on 2016/11/4.
 */

public class ExerciseHistoryAdapter extends BaseAdapter {
    private List<EvaluatorModeEntity> list;
    private Context mContext;
    private DisplayImageOptions defaultOptions;
//    private BitmapFactory.Options options;

    @Override
    public int getCount() {
        return list.size();
    }

    public ExerciseHistoryAdapter(Context mContext, List<EvaluatorModeEntity> list) {
        this.list = list;
        this.mContext = mContext;

        defaultOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.img_disney) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.img_disney)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.img_disney)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
//                .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
//                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
//                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
//                .decodingOptions(options)//设置图片的解码配置
//                .delayBeforeLoading(0)//int delayInMillis为你设置的下载前的延迟时间
                //设置图片加入缓存前，对bitmap进行设置
                //.preProcessor(BitmapProcessor preProcessor)
//                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                .displayer(new RoundedBitmapDisplayer(50))//不推荐用！！！！是否设置为圆角，弧度为多少
//                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间，可能会出现闪动
                .build();//构建完成
    }

    public void setData(List<EvaluatorModeEntity> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder mHolder = null;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.exercisehistory_item, parent, false);
            mHolder = new ViewHolder();
            mHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
            mHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        String url = Constants.SERVER_HOST + "/images/" + list.get(position).getImagePath();
        ImageLoader.getInstance().displayImage(url, mHolder.iv_image, defaultOptions, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                Bitmap b = imageCompress(loadedImage, 200, 200);
                if (view != null && b != null)
                    ((ImageView) view).setImageBitmap(b);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
        mHolder.tv_name.setText("" + list.get(position).getName());
        return convertView;
    }

    /**
     * 获取单个实体
     */
    public EvaluatorModeEntity getModeEntry(int pos){
        if(pos >= list.size()){
            return null;
        }
        return list.get(pos);
    }

    static class ViewHolder{
        public ImageView iv_image;
        public TextView tv_name;
    }

    /**
     * 图片压缩
     * @param image
     * @param pixelW
     * @param pixelH
     * @return
     */
    public Bitmap imageCompress(Bitmap image, float pixelW, float pixelH) {
        if(image == null){
            return null;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, os);
        if( os.toByteArray().length / 1024>1024) {//大于1M,进行压缩避免OOM
            os.reset();
            image.compress(Bitmap.CompressFormat.PNG, 50, os);//压缩50%
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;
        float ww = pixelW;
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        return bitmap;
    }
}
